<template>
  <div class="admin-container">
    <!-- 搜索栏 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="文件名">
          <el-input
            v-model="searchForm.fileName"
            style="width: 180px"
            placeholder="请输入文件名"
            clearable
          />
        </el-form-item>
        <el-form-item label="求职者">
          <el-input
            v-model="searchForm.seekerName"
            style="width: 180px"
            placeholder="请输入求职者姓名"
            clearable
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="待审核" value="pending" />
            <el-option label="已通过" value="approved" />
            <el-option label="已驳回" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            搜索
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 错误提示 -->
    <el-alert
      v-if="error"
      :title="error"
      type="error"
      show-icon
      closable
      @close="clearError"
      style="margin-bottom: 20px;"
    />

    <!-- 表格 -->
    <el-card>
      <div class="table-header">
        <h3>求职材料审核列表</h3>
        <div>
          <el-button @click="refreshData" :loading="loading">
            刷新
          </el-button>
          <el-button type="primary" @click="exportData">
            导出
          </el-button>
        </div>
      </div>

      <el-table :data="documents" style="width: 100%" v-loading="loading">
        <el-table-column label="序号" type="index" width="60" />
        <el-table-column prop="fileName" label="文件名" width="200" show-overflow-tooltip />
        <el-table-column prop="seekerName" label="求职者" width="120" />
        <el-table-column prop="fileType" label="类型" width="80">
          <template #default="{ row }">
            <el-tag :type="row.fileType === 'pdf' ? 'danger' : 'primary'">
              {{ row.fileType?.toUpperCase() }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="fileSize" label="大小" width="100">
          <template #default="{ row }">
            {{ formatFileSize(row.fileSize) }}
          </template>
        </el-table-column>
        <el-table-column prop="uploadTime" label="上传时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.uploadTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              @click="handlePreview(scope.row)"
              :loading="previewLoading === scope.row.id"
            >
              预览
            </el-button>
            <el-button
              size="small"
              @click="handleDownload(scope.row)"
              :loading="downloadLoading === scope.row.id"
            >
              下载
            </el-button>
            <el-button
              size="small"
              type="success"
              @click="handleApprove(scope.row)"
              :disabled="scope.row.status !== 'pending'"
              :loading="approveLoading === scope.row.id"
            >
              通过
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleReject(scope.row)"
              :disabled="scope.row.status !== 'pending'"
              :loading="rejectLoading === scope.row.id"
            >
              驳回
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </el-card>

    <!-- 驳回对话框 -->
    <el-dialog
      v-model="rejectDialogVisible"
      title="驳回理由"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="rejectForm">
        <el-form-item label="驳回理由">
          <el-input
            v-model="rejectForm.comments"
            type="textarea"
            :rows="4"
            placeholder="请输入驳回理由"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="confirmReject"
            :loading="rejectLoading !== null"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useDocumentsStore } from "@/store/document.js";
import { storeToRefs } from 'pinia'
import { ElMessage, ElMessageBox } from 'element-plus'
import { documentService } from '@/service/document'

const documentsStore = useDocumentsStore()
const { documents, pagination, loading, error } = storeToRefs(documentsStore)

const searchForm = reactive({
  fileName: '',
  seekerName: '',
  status: ''
})

const rejectDialogVisible = ref(false)
const currentRejectDoc = ref(null)
const rejectForm = reactive({ comments: '' })
const approveLoading = ref(null)
const rejectLoading = ref(null)
const previewLoading = ref(null)
const downloadLoading = ref(null)

const formatFileSize = (bytes) => {
  if (!bytes) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleString('zh-CN')
}

const getStatusTagType = (status) => {
  const types = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已驳回'
  }
  return texts[status] || status
}

/*const handlePreview = async (row) => {
  try {
    previewLoading.value = row.id

    // 使用service方法获取blob数据
    const blobData = await documentService.preview(row.id)

    const blob = new Blob([blobData], {
      type: row.fileType === 'pdf'
        ? 'application/pdf'
        : 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    })

    const url = window.URL.createObjectURL(blob)
    const previewWindow = window.open(url, '_blank')

    if (!previewWindow) {
      ElMessage.warning('请允许浏览器弹出窗口以预览文件')
      // 备选方案：提供下载
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', row.fileName)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }

    // 清理URL对象
    setTimeout(() => {
      window.URL.revokeObjectURL(url)
    }, 1000)

  } catch (error) {
    console.error('预览失败:', error)
    ElMessage.error(`预览失败: ${error.message || '请稍后重试'}`)
  } finally {
    previewLoading.value = null
  }
}

const handleDownload = async (row) => {
  try {
    downloadLoading.value = row.id

    // 使用service方法获取blob数据
    const blobData = await documentService.download(row.id)

    const blob = new Blob([blobData])
    const url = window.URL.createObjectURL(blob)

    // 创建下载链接
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', row.fileName)
    document.body.appendChild(link)
    link.click()

    // 清理
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    ElMessage.success('下载成功')

  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error(`下载失败: ${error.message || '请稍后重试'}`)
  } finally {
    downloadLoading.value = null
  }
}*/
// 在 AdminView.vue 的 script 部分
const handleDownload = async (row) => {
  try {
    downloadLoading.value = row.id;

    // 使用 service 方法获取 blob 数据
    const blobData = await documentService.download(row.id);

    if (!blobData) {
      throw new Error('未找到文件内容');
    }

    // 创建 blob URL
    const blob = new Blob([blobData], {
      type: row.fileType === 'pdf'
        ? 'application/pdf'
        : 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    });

    const url = window.URL.createObjectURL(blob);

    // 创建下载链接
    const link = document.createElement('a');
    link.href = url;
    link.download = row.fileName;
    document.body.appendChild(link);
    link.click();

    // 清理
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    ElMessage.success('下载成功');

  } catch (error) {
    console.error('下载失败:', error);
    ElMessage.error(`下载失败: ${error.message || '请稍后重试'}`);
  } finally {
    downloadLoading.value = null;
  }
}

const handlePreview = async (row) => {
  try {
    previewLoading.value = row.id;

    // 使用 service 方法获取 blob 数据
    const blobData = await documentService.preview(row.id);

    if (!blobData) {
      throw new Error('未找到文件内容');
    }

    // 创建 blob URL
    const blob = new Blob([blobData], {
      type: row.fileType === 'pdf'
        ? 'application/pdf'
        : 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    });

    const url = window.URL.createObjectURL(blob);

    // 尝试在新窗口打开
    const previewWindow = window.open(url, '_blank');

    if (!previewWindow) {
      // 如果弹窗被阻止，提供下载
      ElMessage.warning('请允许浏览器弹出窗口以预览文件');
      const link = document.createElement('a');
      link.href = url;
      link.download = row.fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }

    // 清理 URL 对象
    setTimeout(() => {
      window.URL.revokeObjectURL(url);
    }, 1000);

  } catch (error) {
    console.error('预览失败:', error);
    ElMessage.error(`预览失败: ${error.message || '请稍后重试'}`);
  } finally {
    previewLoading.value = null;
  }
}
const handleApprove = async (row) => {
  try {
    await ElMessageBox.confirm('确定通过该文档？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    approveLoading.value = row.id
    await documentsStore.approveDocument(row.id, '管理员')
    ElMessage.success('审核通过成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '操作失败')
    }
  } finally {
    approveLoading.value = null
  }
}

const handleReject = (row) => {
  currentRejectDoc.value = row
  rejectForm.comments = ''
  rejectDialogVisible.value = true
}

const confirmReject = async () => {
  if (!rejectForm.comments.trim()) {
    return ElMessage.warning('请输入驳回理由')
  }

  try {
    rejectLoading.value = currentRejectDoc.value.id
    await documentsStore.rejectDocument(
      currentRejectDoc.value.id,
      '管理员',
      rejectForm.comments
    )
    ElMessage.success('已驳回')
    rejectDialogVisible.value = false
  } catch (error) {
    ElMessage.error(error.message || '操作失败')
  } finally {
    rejectLoading.value = null
  }
}

const handleSearch = () => {
  documentsStore.searchDocuments(searchForm)
}

const resetSearch = () => {
  searchForm.fileName = ''
  searchForm.seekerName = ''
  searchForm.status = ''
  documentsStore.searchDocuments(searchForm)
}

const handlePageChange = (page) => {
  documentsStore.changePage(page)
}

const handleSizeChange = (size) => {
  documentsStore.changePageSize(size)
}

const refreshData = () => {
  documentsStore.fetchDocuments()
}

const exportData = () => {
  ElMessage.info('导出功能开发中')
}

const clearError = () => {
  documentsStore.clearError()
}

onMounted(() => {
  documentsStore.fetchDocuments()
})
</script>

<style scoped>
.admin-container {
  width: 100%;
  min-height: 100%;
  padding: 20px;
  box-sizing: border-box;
}

.filter-card {
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-header h3 {
  margin: 0;
  color: #303133;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

:deep(.el-table .cell) {
  white-space: nowrap;
}

:deep(.el-table .el-tag) {
  margin: 2px;
}

.dialog-footer {
  text-align: right;
}
</style>
